const express = require('express')
const mongoose = require('mongoose')
const Grid = require('gridfs-stream')
const multer = require('multer')
const multerGridFsStorage = require('multer-gridfs-storage')
const path = require('path')
const fs = require('fs')

const app = express()
const port = 3000

// MongoDB URI
const mongoURI = 'mongodb://localhost:27017/account' // 替换为你的数据库名称

// Create mongo connection
const conn = mongoose.createConnection(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })

// Initialize gfs
let gfs
conn.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo)
  gfs.collection('uploads') // Set the collection to store files
})

// Create storage engine
const storage = new multerGridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return {
      filename: file.originalname,
      bucketName: 'uploads' // Set the name of the collection
    }
  }
})

const upload = multer({ storage })

// Upload route
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully!')
})

// Start server
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`)
})

// Function to upload local file
const uploadLocalFile = (filePath) => {
  const fileStream = fs.createReadStream(filePath)
  const writeStream = gfs.createWriteStream({
    filename: path.basename(filePath),
    bucketName: 'uploads'
  })

  fileStream.pipe(writeStream)

  writeStream.on('close', (file) => {
    console.log(`${file.filename} uploaded successfully!`)
  })
}

// Upload the local file
uploadLocalFile('C:\\Users\\Gaogy\\Pictures\\临时\\adai.jpg') // 替换为你的文件路径
